<?php

namespace App\Http\Controllers;

use App\Models\ProposalReport;
use App\Models\TopicSelection;
use Illuminate\Http\Request;

class ProposalReportController extends Controller
{
    public function index()
    {
        $reports = ProposalReport::with(['topicSelection.student.user', 'topicSelection.thesisTopic.teacher.user'])->get();
        return response()->json($reports);
    }

    public function store(Request $request)
    {
        $request->validate([
            'selection_id' => 'required|exists:topic_selections,id',
            'content' => 'required|string',
        ]);

        $selection = TopicSelection::findOrFail($request->selection_id);
        if ($selection->status !== 'approved') {
            return response()->json(['message' => 'Topic selection must be approved first'], 422);
        }

        $report = ProposalReport::create([
            'selection_id' => $request->selection_id,
            'content' => $request->content,
            'status' => 'draft',
        ]);

        return response()->json($report->load(['topicSelection.student.user', 'topicSelection.thesisTopic.teacher.user']), 201);
    }

    public function show(ProposalReport $report)
    {
        return response()->json($report->load(['topicSelection.student.user', 'topicSelection.thesisTopic.teacher.user']));
    }

    public function update(Request $request, ProposalReport $report)
    {
        $request->validate([
            'content' => 'string',
            'status' => 'in:draft,submitted,approved',
        ]);

        if ($request->has('status') && $request->status === 'submitted') {
            $request->merge(['submitted_at' => now()]);
        } elseif ($request->has('status') && $request->status === 'approved') {
            $request->merge(['approved_at' => now()]);
        }

        $report->update($request->all());
        return response()->json($report->load(['topicSelection.student.user', 'topicSelection.thesisTopic.teacher.user']));
    }

    public function destroy(ProposalReport $report)
    {
        $report->delete();
        return response()->json(null, 204);
    }
} 